import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import sha1 from 'js-sha1'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    user: '' // 用户详细信息
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER: (state, user) => {
    state.user = user
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { phoneNumber, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ phoneNumber: phoneNumber.trim(), password: sha1(password), clientType: 'webBrowser' }).then(res => {
        const { success, message, data } = res || {}
        const { access_token } = data || {}
        if (success && access_token) {
          // {"access_token":"","token_type":"","refresh_token":"","expires_in":"","scope":"","jti":""}
          const now = new Date().getTime()
          data.expireTime = new Date(now + data.expires_in * 1000)
          const token = JSON.stringify(data)
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        } else {
          reject(message)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  updateUserNickname({ commit, state }, { nickname }) {
    return new Promise(resolve => {
      const u = state.user ? JSON.parse(state.user) : {}
      u.nickname = nickname
      commit('SET_USER', JSON.stringify(u))
      resolve()
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { success, message, data } = response
        if (success) {
          commit('SET_NAME', data.phoneNumber)
          commit('SET_AVATAR', '')
          commit('SET_USER', JSON.stringify(data))
          resolve(response)
        } else {
          reject(message)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

